package com.cloudcc.mobile.view.test;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import com.cloudcc.cloudframe.adapter.ViewHolder;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.LoginEvent;
import com.cloudcc.cloudframe.bus.EventList.ServerUrlEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.net.async.JsonRequest;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.AppManager;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.BaseOneChoiceAdapter;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.LoginPresenter;
import com.cloudcc.mobile.util.AESUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UIUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.wel.GuideViewActivity;
import com.google.gson.JsonObject;
import com.litesuits.android.log.Log;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 快速进入第三步 选择角色
 *
 * @author wangzhiqiang
 * @Description: TODO()
 * @date 2016-3-3 下午3:44:34
 */
public class Step3Fragment extends BaseStepFragment implements IEventLife {

    private String mEns = RunTimeManager.getInstance().getlanguage();
    private int mFroms = 11;
    @Bind(R.id.listview)
    ListView mlistView;
    private LoginPresenter loginPresenter = new LoginPresenter();
    private RoleChoiceAdapter mAdapter;

    private RoleTestUserName roleTestUser;

    @Override
    public void init() {
        super.init();
        register();

        initChoiceData();

    }

    private void initChoiceData() {
        List<RoleTestUserName> datas = new ArrayList<RoleTestUserName>();


        if ("en".equals(mEns)) {
            datas.add(new RoleTestUserName("Boss(CEO)", "boss-en@cloudcc.com", "yzegda"));
            datas.add(new RoleTestUserName("Sales Manager / Sales Representative", "sales-en@cloudcc.com",
                    "TswjCy"));
        } else {
            datas.add(new RoleTestUserName("老板(CEO)", "boss@cloudcc.com", "yzegda"));
            datas.add(new RoleTestUserName("销售经理/销售代表", "sales@cloudcc.com",
                    "TswjCy"));
        }

        mAdapter = new RoleChoiceAdapter(getActivity());
        mlistView.setAdapter(mAdapter);
        mAdapter.changeData(datas);
    }

    @OnClick(R.id.test_done)
    public void clickDone() {

        if (mAdapter == null) {
            return;
        }

        roleTestUser = mAdapter.getItem(mAdapter.getSelectPost());
        loginPresenter.getAppUrl(roleTestUser.userName);
        // String url = "http://app9.cloudcc.com";
        // String url = "http://demo.cloudcc.com";
        // UrlTools.url = url + "/";
        // UrlManager.APP_UR = url;
        // UrlTools.weixinUrl = url;


        if ("en".equals(mEns)) {
            showWainting("Please wait...");
        } else {
            showWainting("请稍等...");
        }

        // loginPresenter.login(roleTestUser.userName, roleTestUser.password);

    }

    public void onEventMainThread(ServerUrlEvent event) {
        if (event.isError()) {
            dismissWainting();
            Tools.showInfo(mContext, event.getMessage());
            return;
        }
        String url = event.getData().data.url;
        UrlTools.url = url + "/";
        UrlManager.APP_UR = url;
        UrlTools.weixinUrl = url;
        Log.d("loginurl", "loginurl" + url);
        loginPresenter.login(roleTestUser.userName, roleTestUser.password);
    }

    /**
     * 登录数据返回
     *
     * @param event
     */
    int i = 0;

    public void onEventMainThread(LoginEvent event) {
        if (event.isError()) {

            i++;
            if (i > 4) {
                dismissWainting();


                if ("en".equals(mEns)) {
                    showToast("Pro, sorry to log in failed, please try again。。。");
                } else {
                    showToast("亲,不好意思登录失败,请重新尝试体验。。。");
                }

            } else {
                // showToast("第"+i+1+"一次登录失败，正在进行第"+i+2+"次");
                Log.d("teldenglu", "第" + i + 1 + "一次登录失败，正在进行第" + i + 2 + "次");
                loginPresenter.login(roleTestUser.userName,
                        roleTestUser.password);
            }
            return;

        }
        String enPassword = StringUtils.EMPTY;
        try {
            enPassword = AESUtils.encrypt(Tools.getpassword(),
                    roleTestUser.password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(enPassword)) {// 将用户名密码保存到db中记录
            loginPresenter.saveLoginToHistory(roleTestUser.userName,
                    enPassword, false, false, false);
        }
        RunTimeManager.setorgId((event.getData().userInfo.orgId));
        RunTimeManager.setAppBinding(event.getData().binding);
        RunTimeManager.getInstance().setTestModel(true);
        final UserModel user = event.getData().userInfo;
        UserManager.getManager().saveUser(user);
        //		insertLeads();
        enterAPP(mFroms);

    }

    /**
     * 插入潜在客户
     */
    private void insertLeads() {
        HashMap<String, String> data = new HashMap<String, String>();


        if ("en".equals(mEns)) {
            data.put("name", "Andrews mobile phone fast experience");
        } else {
            data.put("name", "安卓手机快速体验");
        }

        data.put("phone", mParentActivity.getTestPhoneMobile());
        //		data.put("isMobile", "true");
        data.put("isMobileRegister", "true");
        List aa = new ArrayList();
        aa.add(data);
        RequestParams params = new RequestParams();
        params.put("serviceName", "insert");
        params.put("objectApiName", "Lead");
        params.put("data", GsonUtil.Object2Json(aa));
        params.put("binding", mParentActivity.testBinding);
        AsyncClient.getInstance().post(
                "http://app.cloudcc.com/distributor.action", params,
                new myJsonRequest());
    }

    private class myJsonRequest extends JsonRequest {

        @Override
        public void handleFailure(ErrorInfo arg0) {
            dismissWainting();
            // loginPresenter.login(roleTestUser.userName,
            // roleTestUser.password);
            Log.d("logintiyan", "体验账号：" + roleTestUser.userName
                    + roleTestUser.password);
            // insertLeads();
            enterAPP(mFroms);
        }

        @Override
        public void handleSuccess(JsonObject arg0, String arg1) {
            dismissWainting();
            Log.d("logintiyan", "体验账号成功：" + roleTestUser.userName
                    + roleTestUser.password);
            enterAPP(mFroms);
        }
    }

    /**
     * 进入app
     */
    private void enterAPP(int mFroms) {
        AppContext.isFenXiang = false;
        UIUtils.enterMainUI(mContext,mFroms);
        AppManager.getInstance().finishActivity(GuideViewActivity.class);
        getActivity().finish();
    }

    private class RoleTestUserName {
        public RoleTestUserName(String title, String userName, String password) {
            super();
            this.title = title;
            this.userName = userName;
            this.password = password;
        }

        public String title;
        public String userName;
        public String password;

    }

    private class RoleChoiceAdapter extends
            BaseOneChoiceAdapter<RoleTestUserName> {

        public RoleChoiceAdapter(Context mContext) {
            super(mContext);
        }

        @Override
        public int getLayoutId() {
            return R.layout.role_list_item;
        }

        @Override
        public void convert(ViewHolder h, RoleTestUserName t) {
            h.setText(R.id.tv1, t.title);
            ImageView image = h.getView(R.id.iv1);
            if (mSelectPos == h.getPostion()) {
                image.setImageResource(R.drawable.added_item);
                if ("老板(CEO)".equals(t.title)) {
                    mFroms = 11;
                }else if(t.title.contains("Boss")){
                    mFroms = 11;
                }else{
                    mFroms = 22;
                }
            } else {
                image.setImageDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
            final int pos = h.getPostion();
            final RoleTestUserName tt = t;
            h.getConvertView().setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    mSelectPos = pos;
                    String s = tt.title;
                    String ss = s;
                    notifyDataSetChanged();
                }
            });

        }

    }

    @Override
    public void onDestroy() {
        unRegister();
        super.onDestroy();
    }

    @Override
    public int getLayoutId() {
        return R.layout.test_step3;
    }

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

}
